
package com.baseframe.gateway.filter;

import com.baseframe.auth.props.AuthProvider;
import com.baseframe.auth.utils.TokenUtil;
import com.baseframe.jwt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * webflux 日志请求记录，方便开发调试。请求日志过滤器排序尽量低。
 *
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(value = "base.log.request.enabled", havingValue = "true", matchIfMissing = true)
public class BaseGlobalRequestLogFilter implements GlobalFilter, Ordered {
//	private final WebEndpointProperties endpointProperties;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		// 打印请求路径
		String path = request.getPath().pathWithinApplication().value();

//		// 忽略 endpoint 请求
//		String endpointBasePath = endpointProperties.getBasePath();
//		if (StringUtils.isNotBlank(endpointBasePath) && path.startsWith(endpointBasePath)) {
//			return chain.filter(exchange);
//		}

		String requestUrl = getOriginalRequestUrl(exchange);

		// 构建成一条长 日志，避免并发下日志错乱
		StringBuilder beforeReqLog = new StringBuilder(300);
		// 日志参数
		List<Object> beforeReqArgs = new ArrayList<>();
		beforeReqLog.append("\n\n================ Gateway Request Start  ================\n");
		// 打印路由
		beforeReqLog.append("===> {}: {}\n");
		// 参数
		String requestMethod = request.getMethodValue();
		beforeReqArgs.add(requestMethod);
		beforeReqArgs.add(requestUrl);

		// 打印请求头
		HttpHeaders headers = request.getHeaders();
		headers.forEach((headerName, headerValue) -> {
			beforeReqLog.append("===Headers===  {}: {}\n");
			beforeReqArgs.add(headerName);
			if (AuthProvider.AUTH_KEY.toLowerCase().equals(headerName)) {
				String value = headerValue.get(0);
				String token = TokenUtil.stripOffPrefixes(value);
				Claims claims = JwtUtil.getClaims(token);
				beforeReqArgs.add((claims == null) ? "" : claims.toString());
				beforeReqLog.append("===Headers===  {}: {}\n");
				beforeReqArgs.add(headerName.concat("-original"));
				beforeReqArgs.add(StringUtils.join(headerValue.toArray()));
			} else {
				beforeReqArgs.add(StringUtils.join(headerValue.toArray()));
			}
		});

		beforeReqLog.append("================  Gateway Request End  =================\n");
		// 打印执行时间
		log.info(beforeReqLog.toString(), beforeReqArgs.toArray());
		return chain.filter(exchange);
	}

	private String getOriginalRequestUrl(ServerWebExchange exchange) {
		ServerHttpRequest request = exchange.getRequest();

		LinkedHashSet<URI> uris = exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);

		URI requestUri = uris.stream().findFirst().orElse(request.getURI());

		MultiValueMap<String, String> queryParams = request.getQueryParams();

		return UriComponentsBuilder.fromPath(requestUri.getRawPath()).queryParams(queryParams).build().toUriString();
	}

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}
}
